var client = require('../redis');
var async = require('async');
var _ = require('lodash');

var Session = {

	/*
	 * user {
	 *		sessionId : xxxxx,
     *		...{user} user其它属性
	 * }
	*/
	create : function(user, callback){

		async.waterfall([
			function(callback){
				//sessionSet里存放了当前登录用户的sessionId
				client.sadd('sessionSet', user.sessionId, function(err,ret){
					callback(err,user.sessionId);
				});
			},
			function(sessionId,callback){
				var sessionData = _.omit(user, 'sessionId');
				client.hset('sessionHash' , sessionId , JSON.stringify(sessionData) , function(err,ret){
					callback(err,sessionData);
				});
			}
		],function(err,sessionData){
			callback(err,sessionData);
		});

	},

	delete : function(sessionId,callback){

		async.parallel([
			function(callback){
				client.srem('sessionSet',sessionId,function(err,ret){
					callback(err,ret);
				});
			},
			function(callback){
				client.hdel('sessionHash' , sessionId , function(err,ret){
					callback(err,ret);
				});
			}
		],function(err,results){
			callback(err,results);
		});

	},

	getSessionById : function(sessionId, callback){

		async.waterfall([
			function(callback){
				client.sismember('sessionSet',sessionId,function(err,isLogin){
					callback(err,isLogin);
				});
			},
			function(isLogin,callback){

				if(isLogin){
					client.hget('sessionHash' , sessionId , function(err,sessionData){
						callback(err,JSON.parse(sessionData));
					});
				}
				else{
					callback(err,null);
				}
				
			}
		],function(err,sessionData){
			callback(err,sessionData);
		});

	},

	isLogin : function(sessionId , callback){

		client.sismember('sessionSet',sessionId,function(err,isLogin){
			callback(err,isLogin);
		});

	}

};

module.exports = Session;